
<template>

  <el-card class="max-width: auto">
    <template #header>
      <h2>歌曲管理</h2>
      <div class="card-header" >
        
          <el-input v-model="searchname" style="width: 240px" placeholder="输入歌曲名称进行查询" />
          &nbsp;&nbsp;
          <el-input v-model="searchmanname" style="width: 240px" placeholder="输入音乐人姓名进行查询" />
          &nbsp;&nbsp;
          <el-select v-model="searchtype" style="width: 240px" placeholder="选择歌曲类型" @change="searchMusic">
            <el-option label="所有歌曲类型" value=""></el-option>
            <el-option label="新国风流行" value="新国风流行"></el-option>
            <el-option label="传统音乐" value="传统音乐"></el-option>
            <el-option label="戏曲文化" value="戏曲文化"></el-option>
            <el-option label="主题文化" value="主题文化"></el-option>
            <el-option label="地域特色" value="地域特色"></el-option>
          </el-select>

          &nbsp;&nbsp;
          <el-button type="primary" round @click="searchMusic">查询</el-button>
          <el-button type="success" round @click="openAddDialog">添加</el-button>&nbsp;&nbsp;
          <el-button type="warning" round @click="multiDelete">多选删除</el-button>
          <audio ref="audioPlayer" controls v-if="currentAudio" :src="'http://localhost:8080/images/upload/'+currentAudio">
      您的浏览器不支持音频播放。
    </audio>
      </div>
    </template>

    <!-- 表格区域 -->
    <el-table
      :data="musics"
      style="width: 150%"
      @selection-change="handleSelectionChange"
      ref="multipleTable"
      stripe highlight-current-row border
    >
      <el-table-column
        type="selection"
        width="100">
      </el-table-column>
      <!-- <el-table-column prop="music_id" label="序号" width="100" /> -->
      <el-table-column label="序号" type="index" width="50" align="center"></el-table-column>

      <el-table-column prop="cover_image" label="歌曲封面" width="120" >      
        <template #default="scope">
          <el-image
            style="width: 100px; height: 100px"
           :src="'http://localhost:8080/images/upload/' + scope.row.cover_image"/>
          </template>
      </el-table-column>

 
      <el-table-column prop="music_name" label="乐曲名" width="120" />
      <el-table-column prop="artist" label="音乐人" width="120" />
      <el-table-column prop="duration" label="歌曲播放量" width="120" />
      
      <el-table-column prop="type" label="歌曲类型" width="120" />
      <!-- 操作列 -->
      <el-table-column fixed="right" label="Operations" min-width="120">
        <template v-slot="scope">
          <el-button type="warning" @click="confirmDeleteMusic(scope.row)">删除</el-button>
          <el-button type="info" @click="openDetailDialog(scope.row.music_id)">详情</el-button>
          <el-button type="primary" @click="playMusic(scope.row.audio,scope.row.music_id)">播放</el-button>
       
          <el-button type="info" @click="openDialog(false, scope.row.music_id)">编辑</el-button>
        
        </template>
      </el-table-column>
    </el-table>
     <!-- 分页显示 -->
     <el-pagination
          :current-page.sync="currentPage"
          :page-size="pageSize"
          :total="totalItems"
          layout="prev, pager, next"
          @current-change="handlePageChange"
        />
    <!--分页！！！-->
    




</el-card>
    <!-- 添加对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogFormVisible"
      width="50%"
      @close="resetForm">
      <!-- 表单内容 -->
  
      <el-form
      :model="form">
        <el-row :gutter="20">
        <el-col :span="10">

        <el-form-item label="歌曲名称" :label-width="formLabelWidth">
          <el-input v-model="form.music_name" ></el-input>
        </el-form-item>

        <el-form-item label="歌曲作者" :label-width="formLabelWidth">
          <el-input v-model="form.artist" ></el-input>
        </el-form-item>
        
        <el-form-item label="歌曲类型" :label-width="formLabelWidth">
        <el-select v-model="form.type" placeholder="请选择歌曲类型">
          <el-option label="传统音乐" value="传统音乐"></el-option>
          <el-option label="新国风流行" value="新国风流行"></el-option>
          <el-option label="戏曲融合" value="戏曲融合"></el-option>
          <el-option label="主题文化" value="主题文化"></el-option>
          <el-option label="地域特色" value="地域特色"></el-option>
        </el-select>
      </el-form-item>

        <el-form-item label="歌曲时长" :label-width="formLabelWidth">
          <el-input v-model="form.popularity" ></el-input>
        </el-form-item>
        <el-form-item label="歌曲播放量" :label-width="formLabelWidth">
          <el-input v-model="form.duration" ></el-input>
        </el-form-item>

        <el-form-item label="歌词" :label-width="formLabelWidth">
          <el-input v-model="form.lyrics"type ="textarea"></el-input>
        </el-form-item>
       
       
        <el-form-item label="歌曲简介" :label-width="formLabelWidth">
          <el-input v-model="form.description"type ="textarea"></el-input>
        </el-form-item>
     

            </el-col>
              <el-col :span="6">
                <el-upload
                  class="avatar-uploader"
                  action="http://localhost:8080/music/upload"
                  :show-file-list="false"
                  :on-success="handleSuccess">
                  <img v-if="form.cover_image" :src="'http://localhost:8080/images/upload/'+form.cover_image" class="avatar" />
                  <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>   
                </el-upload>
                <br>
                
                <el-upload
            class="audio-uploader"
            action="http://localhost:8080/music/upload"
            :show-file-list="false"
            :on-success="handleMusicSuccess"
            :accept="'audio/*'"
          >
            <template #default>
              <!-- 如果已经上传音频，显示音频播放器 -->
              <div v-if="form.audio">
                <audio controls style="width: 100%;">
                  <source :src="'http://localhost:8080/images/upload/' + form.audio" type="audio/mpeg" />
                  您的浏览器不支持音频播放。
                </audio>
                <a href="#">上传成功</a>
              </div>
              <!-- 如果未上传音频，显示上传按钮 -->
              <el-button v-else type="primary" style="display: flex; align-items: center; justify-content: center; padding: 8px 16px;">
                <el-icon-upload style="margin-right: 8px; font-size: 18px;" />
                <span>上传音频</span>
              </el-button>
            </template>
          </el-upload>  


          <br>
    
            </el-col>
        <br>
        
      </el-row>
        <!-- 根据需要添加更多的表单项 -->
      </el-form>
      <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addMusic">确 定</el-button>
      </div>
    </template>
    </el-dialog>




<!-- 详细对话框 -->

<el-dialog
  title="歌曲详情"
  v-model="dialogDetailVisible"
  width="1000"
  @close="resetForm">
  
  <el-form :model="form">
    <el-row>
      <el-col :span="12">
        <el-form-item label="歌曲名称" :label-width="formLabelWidth">
          <el-form-item :label="form.music_name" >
          </el-form-item>
        </el-form-item>
        <br>
        <el-form-item label="歌曲作者" :label-width="formLabelWidth">
          <el-form-item :label="form.artist" >
          </el-form-item>
        </el-form-item>
        <br>
        <el-form-item label="歌曲类型" :label-width="formLabelWidth">
          <el-form-item :label="form.type" >
          </el-form-item>
        </el-form-item>
        <br>
        <el-form-item label="歌曲播放量" :label-width="formLabelWidth">
          <el-form-item :label="form.duration" >
          </el-form-item>
        </el-form-item>
        
   
     
    
      </el-col>
      <el-col :span="12">
        <!-- 歌词 -->
        <el-form-item label="歌词" :label-width="formLabelWidth">
          <el-input
            type="textarea"
            v-model="form.lyrics"
            readonly
            class="text-area-scrollable"
            :rows="8"> <!-- 设置行数为5，根据需要调整 -->
          </el-input>
        </el-form-item>
        <br>
        <el-form-item label="歌曲简介" :label-width="formLabelWidth">
          <el-input
          type="textarea"
          v-model="form.description"
          readonly
          class="text-area-scrollable"
          :rows="8"> <!-- 设置行数为5，根据需要调整 -->
          </el-input>
        </el-form-item>
      </el-col>
    </el-row>
    <!-- 根据需要添加更多的表单项 -->
  </el-form>
  <template #footer>
    <div class="dialog-footer">
      <el-button @click="dialogDetailVisible = false">取消</el-button>
    </div>
  </template>
</el-dialog>
 

</template>

<script>

import { ElMessage,ElMessageBox } from 'element-plus';
import { Plus } from '@element-plus/icons-vue'
export default {
  data() {
    return {
      searchname: '', // 搜索框绑定的值，歌曲名称
      searchmanname: '', // 搜索框绑定的值,音乐人
      searchtype: '', // 搜索框绑定的值,音乐类型

      dialogDetailVisible:false, // 详细对话框
      dialogFormVisible: false, // 对话框是否显示
      formLabelWidth: '120px', // 表单项标签宽度
      multipleSelection: [], // 多选删除
      imageUrl:" "   , //图片URL地址
      currentAudio: '', // 当前要播放的音频链接
      pageSize: 4, // 当前页条数
      currentPage: 1, // 当前记录条数
      pageInfo:{},
      

      form: {
        music_name: '',
        artist: '',
        type: '',
        duration: '',
        lyrics: '',
        audio: '',
        cover_image: '',
        description: '',
        celebrity_review: '',
      },
      tableData: [], // 歌曲信息数据
      musics: [], // 所有歌曲数据，用于过滤和删除
      isAdding: false, // 是否为添加模式
      currentMusicId: null, // 当前编辑的歌曲ID

    };
  },
  computed: {

  
  },
  methods: {

    getMusicDetails(music_id) {
  // 根据musicId获取歌曲详情并填充到表单
  this.$http.get(`/music/g1/${music_id}`).then(response => {
    this.form = response.data;
  });
},


    //打开对话框
    openAddDialog() {
  this.isAdding = true; // 设置为添加模式
  this.dialogTitle = '添加歌曲'; // 设置对话框标题
  this.dialogFormVisible = true; // 打开对话框
  this.resetForm(); // 重置表单
},

    // 修改原有的编辑按钮的点击事件
  editMusic(music_id) {
    this.openDialog(false,music_id); // 传入false和musicId表示编辑模式
  },

    //判断对话框
    openDialog(isAdding, music_id) {
  this.isAdding = isAdding;
  this.dialogTitle = isAdding ? '添加歌曲' : '编辑歌曲';
  this.dialogFormVisible = true; // 显示对话框
  if (isAdding) {
    this.resetForm(); // 重置表单
  } else {
    this.getMusicDetails(music_id); // 获取歌曲详情并填充表单
  }
},


   




    handleSuccess(response){      //图片上传成功后的回调函数
      console.log(response);
      this.form.cover_image=response
    },
    handleMusicSuccess(response){      //歌曲成功后的回调函数
      console.log(response);
      this.form.audio=response
    },



       
    playMusic(audio,music_id) { // 将 audioUrl 改为 audio
      console.log(audio,music_id)
      this.currentAudio = audio;  // 设置当前要播放的音频链接
      this.$nextTick(() => {
          console.log("Audio Player:", this.$refs.audioPlayer); // 调试输出
          if (this.$refs.audioPlayer) {
              this.$refs.audioPlayer.load();  // 加载新的音频源
              this.$refs.audioPlayer.play();  // 开始播放
              this.incrementPlayCount(music_id); // 增加播放次数，传递音乐ID
              
          } else {
              console.error("音频播放器引用未定义。");
          }
      });
    },
      incrementPlayCount(music_id) {
      // 发送请求到后端，更新播放次数
      this.$http.post('/music/incrementPlayCount', { music_id }).then(response => {
        // 处理响应
        this.getPageData(this.currentPage, this.pageSize); // 重新获取页面数据以更新播放次数
      }).catch(error => {
        console.error('更新播放次数失败', error);
      });
    },
    handlePageChange(page) {    //更新页码
      console.log("Changing page to:", page); // 调试输出
      this.currentPage = page;
      this.fetchSongs();
    },


    fetchSongs() {
  let params = `page=${this.currentPage}&size=${this.pageSize}`;
  if (this.searchname) {
    params += `&music_name=${encodeURIComponent(this.searchname)}`;
  }
  if (this.searchmanname) {
    params += `&artist=${encodeURIComponent(this.searchmanname)}`;
  }
  if (this.searchtype && this.searchtype !== "所有歌曲类型") {
    params += `&type=${encodeURIComponent(this.searchtype)}`;
  }
  console.log(`Request URL: http://localhost:8080/music/search?${params}`);

  fetch(`http://localhost:8080/music/search?${params}`)
    .then(response => {
      if (!response.ok) {
        throw new Error('Network response was not ok');
      }
      return response.json();
    })
    .then(data => {
      console.log("Fetched data:", data);
      this.musics = data.list;
      this.totalItems = data.total;
      this.currentPage = data.pageNum; // 确保这里更新 currentPage
    })
    .catch(error => console.error('Error fetching songs:', error));
},
   
      
 


    
    searchMusic() {
    this.currentPage = 1; // 重置为第一页
    this.fetchSongs();
  },
    confirmDeleteMusic(music) {         //删除的交互
      this.$confirm(`确定要删除歌曲 ${music.music_name} 吗?`, '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        this.deleteMusic(music.music_id);
      }).catch(() => {
        this.$message.info('删除已取消');
      });
    },
    deleteMusic(music_id) {       //单选删除根据id
      this.$http.delete(`/music/d1/${music_id}`).then(response => {
        if (response.data) {
          this.musics = this.musics.filter(item => item.music_id !== music_id);
          this.tableData = [...this.musics]; // 更新表格数据
          this.$message.success('删除成功');
        } else {
          this.$message.error('删除失败');
        }
      }).catch(error => {
        console.error('删除歌曲失败', error);
        this.$message.error('删除失败，请稍后再试');
      });
    },
    multiDelete() { // 多选删除
      this.$confirm('您确定要删除选中的歌曲吗?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        const musicIds = this.multipleSelection.map(item => item.music_id);
        musicIds.forEach(music_id => {
          this.deleteMusic(music_id);
        });
      }).catch(() => {
        this.$message.info('删除已取消');
      });
    },
    handleSelectionChange(val) {      //多行选择
      this.multipleSelection = val;
    },
  

    //添加和修改歌曲
    addMusic() {
  if (this.isAdding) {
    // 添加歌曲的逻辑
    this.$http.post('/music/hhl', this.form).then(response => {
      if (response.data) {
        this.tableData.push(response.data); // 假设后端返回新添加的歌曲数据
        this.musics.push(response.data); // 更新所有歌曲数据
        this.dialogFormVisible = false; // 关闭对话框
        this.resetForm(); // 清空表单
        this.$message.success('添加成功');
      } else {
        this.$message.error('添加失败');
      }
    }).catch(error => {
      console.error('添加歌曲失败', error);
      this.$message.error('添加失败，请稍后再试');
    });
  } else {
    // 更新歌曲信息的逻辑
    this.$http.put('/music/u1', this.form).then(response => {
      if (response.data) {
        // 更新成功后，需要找到当前歌曲的索引并更新数据
        const index = this.musics.findIndex(item => item.music_id === this.form.music_id);
        if (index !== -1) {
          this.musics.splice(index, 1, this.form); // 更新该歌曲信息
        }
        this.tableData = [...this.musics]; // 重新赋值以更新视图
        this.dialogFormVisible = false; // 关闭对话框
        this.resetForm(); // 清空表单
        this.$message.success('编辑成功');
      } else {
        this.$message.error('编辑失败');
      }
    }).catch(error => {
      console.error('编辑歌曲失败', error);
      this.$message.error('编辑失败，请稍后再试');
    });
  }
},


//打开详情对话框
openDetailDialog(music_id) {
  // 使用箭头函数确保this指向Vue实例
  this.$http.get(`/music/g1/${music_id}`).then((response) => {
    console.log(response.data);
    this.form = response.data; // 确保这里直接赋值给this.form
  }).catch((error) => {
    console.error('获取歌曲详情失败', error);
    this.$message.error('获取歌曲详情失败');
  });
  this.dialogDetailVisible = true;
},


    resetForm() {
      this.form = {
        music_name: '',
        artist: '',
        type: '',
        duration: '',
        lyrics: '',
        audio: '',
        cover_image: '',
        description: '',
        celebrity_review: '',
      };
    },
  },
  components:{
    Plus
  }, 
  created() {  
    this.fetchSongs(); // 组件创建时调用fetchSongs方法，得到歌曲信息  
     },
  mounted() {



  },
};
</script>

<style>
/* 歌词样式 */
#lyrics {
    max-height: 300px;
    overflow-y: auto;
    font-size: 16px;
    line-height: 24px;
}
.highlight {
    color: red;
    font-weight: bold;
}




    .card-header{
      display: flex;
      justify-content: space-between;
    }
    .query{
      display: flex;
      justify-content:space-between;
    }

</style>
<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>

<style scoped>
.text-area-scrollable {
  max-height: 200px; /* 根据需要调整最大高度 */
  overflow-y: auto; /* 超出部分显示滚动条 */
}
</style>

<style scoped>
.text-area-scrollable {
  width: 100%; /* 设置宽度为100%，占满整个表单项的宽度 */
  max-height: 200px; /* 根据需要调整最大高度 */
  overflow-y: auto; /* 超出部分显示滚动条 */
  /* 如果您想要设置最小高度，可以添加如下样式 */
  min-height: 100px; /* 根据需要调整最小高度 */
}
</style>
